package com.alawn.framework.core.web.faces.scope;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.faces.context.FacesContext;

import org.springframework.stereotype.Component;

@Component("pageScope")
public class PageScope implements Map<String, Object> {
	private static final String PAGE_SCOPE_PREFIX = "PAGE";

	public void clear() {
		getPageMap().clear();
	}

	public boolean containsKey(Object key) {
		return getPageMap().containsKey(key);
	}

	public boolean containsValue(Object value) {
		return getPageMap().containsValue(value);
	}

	public Set<Entry<String, Object>> entrySet() {
		return getPageMap().entrySet();
	}

	public Object get(Object key) {
		return getPageMap().get(key);
	}

	public boolean isEmpty() {
		return getPageMap().isEmpty();
	}

	public Set<String> keySet() {
		return getPageMap().keySet();
	}

	public Object put(String key, Object value) {
		return getPageMap().put(key, value);
	}

	public void putAll(Map<? extends String, ? extends Object> m) {
		getPageMap().putAll(m);
	}

	public Object remove(Object key) {
		return getPageMap().remove(key);
	}

	public int size() {
		return getPageMap().size();
	}

	public Collection<Object> values() {
		return getPageMap().values();
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> getPageMap() {
		String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
		Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
		Map<String, Object> pageMap = (Map<String,Object>) sessionMap.get(PAGE_SCOPE_PREFIX + viewId);
		if (pageMap == null) {
			pageMap = new HashMap<>();
			sessionMap.put(PAGE_SCOPE_PREFIX + viewId, pageMap);
		}
		return pageMap;
	}
}
